Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
Recompose "withReducer": justification of async reducer function call

I'm using withReducer HOC and noticed this behaviour: Calling this on click handler for example:

import React from 'react'
import { withReducer } from 'recompose'
import { compose } from 'ramda'

export default compose(
  withReducer('state', 'dispatch', (state, { value }) => {
    console.log(value)
    return { ...state, value }
  }, { value: 'zero' })
)((props) => {
  const { dispatch, state } = props,
    onClick = () => {
      console.log('Hello')
      dispatch({ value: 'one' })
      dispatch({ value: 'two' })
      dispatch({ value: 'three' })
      console.log('World')
    }
  return (
    <div>
      <div>{state.value}</div>
      <button onClick={onClick}>Click me</button>
    </div>
  )
})

It will produce

Hello

World

one

two

three

This means that reduce function is called asynchronously. What is justification for calling it async rather than applying changes to store right away?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The reducer is called asynchronously because we can only use setState to update the tree and setState is asynchronous.

If we call the reducer synchronously, we will need to save the new state somewhere, then call setState and get the new state asynchronously from where we save it. In the end, your tree still get updated asynchronously.

This is why recompose's withReducer() is slightly different from redux. You can think of that withReducer is a simplified version of redux + react-redux's connect().

over 4 years ago · Santiago Trujillo Relatório

0

In this case, dispatch is actually a wrapper for the vanilla API method setState.

React implements setState asynchronously because state transitions are sometimes batched together for performance reasons.

According to the React docs:

setState() does not immediately mutate this.state but creates a pending state transition....There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda